#include"head_2.h"
#include"include/sqlite3.h"

extern pthread_mutex_t mutex_slinklist;
extern pthread_mutex_t mutex_sqlite;

extern pthread_cond_t cond_sqlite;

extern linknode *H_sql;
extern linknode *E_sql;
extern linknode *H_trf;
extern linknode *E_trf;

int create_table(void) {
	
	char sql[1024];
	sqlite3 *db;
	char *errmsg;
	int re;
	
	re = sqlite3_open("my.db", &db);
	if (re != SQLITE_OK) {
		printf("fail to sqlite3_open : %s\n", sqlite3_errmsg(db));
		return;
    }
	
	sprintf (sql,"create table env(temperatureMax float not null,\
									temperatureMin float not null,\
									humidityMax float not null,\
									humidityMin float not null,\
									illuminationMax float not null,\
									illuminationMin float not null,\
									telephoneNum varchar(11) not null,\
									mode int not null,\
									ifnocice int not null,\
									interval int not null,\
									updatePeriod int not null,\
									username varchar(20) not null,\
									password int not null);");
									
	re = sqlite3_exec(db, sql, 0, 0, &errmsg);
	if(re != SQLITE_OK) {
        printf("error:%s\n",  errmsg);
    }
	
	sprintf (sql,"create table collect_env(no int primary key not null,\
											temperatureVal float not null,\
											humidityVal float not null,\
											illuminationVal float not null,\
											envtime varchar(20) not null);");
	
	re = sqlite3_exec(db, sql, 0, 0, &errmsg);
	if(re != SQLITE_OK) {
        printf("error:%s\n",  errmsg);
        return;
    }
	return 0;
}

int init_table_env (void) {

	char sql[1024];
	sqlite3 *db;
	char *errmsg;
	int re;
	
	re = sqlite3_open("my.db", &db);
	if (re != SQLITE_OK) {
		printf("fail to sqlite3_open : %s\n", sqlite3_errmsg(db));
		return -1;
    }
	
	sprintf (sql, "insert into env values(1,25.4,10.5,55.8,10.8,\
											 258,129,'12345678901',1,\
											 2,3,4,'binea',123456);");
	re = sqlite3_exec (db,sql,0,0,&errmsg);
	if (re != SQLITE_OK) {
		printf ("Error:%s",errmsg);
		sqlite3_close (db);
		return 1;
	}
}

int insert_collect_env() {
	
	char sql[1024];
	sqlite3 *db;
	char *errmsg;
	int re;
	linknode *q;
	time_t timep;
	
	pthread_mutex_lock(&mutex_slinklist);
	q = E_sql->next;
	q->next->pro = E_sql;
	E_sql->next = q->next;
	pthread_mutex_unlock(&mutex_slinklist);
	q->next = NULL;
	q->pro = NULL;
	time (&timep);
	
	sprintf (sql, "insert into collect_env values(null,%f,%f,%f,'%s');", (q->env.temp), (q->env.hum), (q->env.ill), asctime(gmtime(&timep)));
	re = sqlite3_exec (db,sql,0,0,&errmsg);
	if (re != SQLITE_OK) {
		printf ("Error:%s",errmsg);
		sqlite3_close (db);
		return 1;
	}
	free(q);
	q = NULL;
}

void * pthread_sqlite(void) {

	create_table();
	init_table_env();
	while(1) {
		pthread_mutex_lock(&mutex_sqlite);
		pthread_cond_wait(&cond_sqlite, &mutex_sqlite);
		pthread_mutex_unlock(&mutex_sqlite);
		
		while((H_sql->next != E_sql) || (E_sql->pro != H_sql)) {
		
			insert_collect_env();
		}

	}
	
}
